package xyz.scootaloo.kami.server.generate.init

import io.vertx.core.CompositeFuture
import io.vertx.core.Future
import xyz.scootaloo.kami.server.model.AccessLevel
import xyz.scootaloo.kami.server.model.AccessToken
import xyz.scootaloo.kami.server.model.AccessType
import xyz.scootaloo.kami.server.model.AccessType.*
import xyz.scootaloo.kami.server.service.RuleSystemService

/**
 * @author flutterdash@qq.com
 * @since 2022/3/26 16:31
 */

class RuleBuilder(
    val path: String,
    var rule: ByteArray = ByteArray(4),
    var limit: Long = 0
) {
    val access: (Int) -> Unit = { rule[ACCESS] = it }
    val download: (Int) -> Unit = { rule[DOWNLOAD] = it }
    val modify: (Int) -> Unit = { rule[MODIFY] = it }
    val define: (Int) -> Unit = { rule[DEFINE] = it }

    fun store(ruleService: RuleSystemService): CompositeFuture {
        val token = AccessToken(path, AccessLevel.SUPER_ADMIN)
        return CompositeFuture.all(
            storeRule(token, ruleService),
            storeLimit(token, ruleService)
        )
    }

    private fun storeRule(token: AccessToken, ruleService: RuleSystemService): Future<Unit> {
        if (rule.any { it > 0 }) {
            return ruleService.createRule(token, rule)
        }
        return Future.succeededFuture()
    }

    private fun storeLimit(token: AccessToken, ruleService: RuleSystemService): Future<Unit> {
        if (limit > 0) {
            return ruleService.createCapLimit(token, limit)
        }
        return Future.succeededFuture()
    }

    private operator fun ByteArray.set(type: AccessType, level: Int) {
        rule[type.key] = level.toByte()
    }
}